package core.modules;
import java.awt.*;
import java.awt.print.*;
 
public class Printer implements Printable {
 
    int[] pageBreaks;  
    String[] textLines;
 
    public int print(Graphics g, PageFormat pf, int pageIndex)
             throws PrinterException {
 
        Font font = new Font("Serif", Font.PLAIN, 14);
        FontMetrics metrics = g.getFontMetrics(font);
        int lineHeight = metrics.getHeight()+20;
 
        if (pageBreaks == null) {
            int linesPerPage = (int)(pf.getImageableHeight()/lineHeight);
            int numBreaks = (textLines.length-1)/linesPerPage;
            pageBreaks = new int[numBreaks];
            for (int b=0; b<numBreaks; b++) {
                pageBreaks[b] = (b+1)*linesPerPage; 
            }
        }
 
        if (pageIndex > pageBreaks.length) {
            return NO_SUCH_PAGE;
        }
 

        Graphics2D g2d = (Graphics2D)g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
 

        int y = 0; 
        int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1];
        int end   = (pageIndex == pageBreaks.length)
                         ? textLines.length : pageBreaks[pageIndex];
        for (int line=start; line<end; line++) {
            y += lineHeight;
            g.drawString(textLines[line], 20, y);
        }
 
        return PAGE_EXISTS;
    }

    public void drukuj(String [] list){
    	textLines = list;
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(this);
        boolean ok = job.printDialog();
        if (ok) {
            try {
                 job.print();
            } catch (PrinterException ex) {
            }
        }
    }
 
    public static void main(String args[]) {
    	new Printer().drukuj(new String[] {"LINE1", "LINE2", "LINE2"});
    }

}